package cn.ncu.wechat.controller;

import cn.ncu.wechat.util.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
public class FilesUpLoadController {
    
    @Value("${upload.path}")
    private String uploadPath;
    
    @PostMapping("/api/upload")
    public Result<?> uploadFiles(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error(400, "上传文件为空");
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + extension;
            
            // 创建目录
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                boolean created = uploadDir.mkdirs();
                log.info("创建上传目录：{}, 结果：{}", uploadPath, created);
            }
            
            // 保存文件
            File destFile = new File(uploadDir, fileName);
            file.transferTo(destFile);
            log.info("文件保存成功：{}", destFile.getAbsolutePath());

            // 如果是图片，获取图片信息
            Map<String, Object> data = new HashMap<>();
            if (isImageFile(fileName)) {
                BufferedImage image = ImageIO.read(destFile);
                if (image != null) {
                    data.put("width", image.getWidth());
                    data.put("height", image.getHeight());
                }
            }

            // 构建访问URL
            String url = "/upload/" + fileName;
            data.put("url", url);
            
            return Result.success(data);

        } catch (Exception e) {
            return Result.error(500, "上传失败：" + e.getMessage());
        }
    }
    
    /**
     * 判断是否为图片文件
     */
    private boolean isImageFile(String fileName) {
        String extension = fileName.toLowerCase();
        return extension.endsWith(".png") || 
               extension.endsWith(".jpg") || 
               extension.endsWith(".jpeg") || 
               extension.endsWith(".gif") || 
               extension.endsWith(".bmp");
    }
}
